﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;

namespace CSharpDuino
{
    public class Program
    {

        public static string buff = string.Empty;
        
        public static Buzz buzz = new Buzz(Pins.GPIO_PIN_D9);

        private static OutputPort R0 = new OutputPort(Pins.GPIO_PIN_D8, false);

        private static Blinker red;
        private static Blinker green;


        private static string password = "1234";

        public static void Main()
        {
            var keyboard = new NumericKeyboard();
            keyboard.KeyPress += new KeyButtonEvent(keyboard_KeyPress);
            keyboard.KeyDown += new KeyButtonEvent(keyboard_KeyDown);

            red = new Blinker(Pins.GPIO_PIN_D13, 62);
            green = new Blinker(Pins.GPIO_PIN_D11, 250);

            var blinker = new Blinker(Pins.ONBOARD_LED, 15);

            var B = new Button(Pins.ONBOARD_SW1);
            B.ButtonClick += foo;

            var blinkerDirection = -1;
            int n = 0;

            while (true)
            {
                keyboard.Read();

                B.ReadState();

                if (blinker.Delay < 10 || blinker.Delay > 250)
                {
                    blinkerDirection *= -1;
                }
                if (n > 500)
                {
                    blinker.Delay = blinker.Delay + (-1 * blinkerDirection) * 10;
                    n = 0;
                }


                n++;
            }

        }

        private static void foo()
        {
            R0.Write(!R0.Read());
        }

        static void keyboard_KeyDown(char c)
        {
            buzz.Beep();
        }

        static void keyboard_KeyPress(char c)
        {
            if (c != '#')
            {
                buff += c.ToString();
            }
            else
            {
                if (buff == password)
                {
                    red.State = false;
                    green.State = true;
                    buzz.Play(2000);
                    buzz.Play(1500);
                    buzz.Play(1000);

                    R0.Write(false);
                }
                else
                {
                    red.State = true;
                    green.State = false;
                    buzz.Play(1000);
                    buzz.Play(1500);
                    buzz.Play(2000);
                    R0.Write(true);
                }

                Debug.Print(buff);
                buff = string.Empty;
                
            }
        }

    }
}
